package com.java.utils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson2.JSONArray;
import com.java.entity.TodoList;

public class FileIo {

	public final static String DBFOLDER = "file";

	public final static String DBSUFFIX = ".todo";

	public final static String DATASPACE = "	";

	private final static String STORAGEFOLDERPATH = Paths.get(DBFOLDER).toAbsolutePath().toString();

	public static void write(String jsonStr) throws Exception {
		try (BufferedWriter writer = new BufferedWriter(
				new FileWriter(STORAGEFOLDERPATH + File.separator + "todoList" + DBSUFFIX))) {
			writer.write(jsonStr);
		} catch (IOException e) {
			throw new Exception(e.getMessage());
		}
	}

	public static List<TodoList> read() throws Exception {
		List<TodoList> list = new ArrayList<TodoList>();
		try (BufferedReader br = new BufferedReader(
				new FileReader(STORAGEFOLDERPATH + File.separator + "todoList" + DBSUFFIX))) {
			StringBuffer sb = new StringBuffer();
			String line = "";
			while ((line = br.readLine()) != null) {
				sb.append(line);
			}
			if (!"".equals(sb.toString())) {
				list = JSONArray.parseArray(sb.toString(), TodoList.class);
			}
		} catch (IOException e) {
			throw new Exception(e.getMessage());
		}
		return list;
	}
}
